<?php
class User extends Animus_FrontEnd_Controller {

    function User() {
        parent :: Animus_FrontEnd_Controller();
        $this->load->model('home/user/User_m');
    }

    function index() {

    }

    function check_login($username, $password) {
        $loginQuery = $this->User_m->loginInfor($username, md5($password));
        if ($loginQuery->num_rows() > 0) {
            return True;
        } else {
            return False;
        }
    }

    function login() {
        $utc = time();
        //validate login form//
        if ($this->input->post('submit')) {
            $formVal = array(
                array(
                    'field' => 'email_login',
                    'Label' => 'Email',
                    'rules' => 'required|valid_email'
                ),
                array(
                    'field' => 'pass_login',
                    'Label' => 'Password',
                    'rules' => 'required'
                )
            );
            $this->form_validation->set_rules($formVal);
            //------------------//
            if ($this->form_validation->run() == TRUE) {
                $email = $this->input->post('email_login');
                $password = md5($this->input->post('pass_login'));
                $query1 = $this->User_m->get_deactivate_user($email);
                if ($query1->num_rows > 0) {
                    $this->_data['login_error'] = "Account is banned!!!";
                    $this->display_view('home/index');
                } else {
                    $query = $this->User_m->get_user($email, $password);
                    if ($query->num_rows > 0) {
                        $login_user = $query->row();
                        $data = array('last_login' => $utc);
                        $this->User_m->change_login_time($data, $login_user->id);
                        $this->session->set_userdata('display_name', $login_user->display_name);
                        $this->session->set_userdata('group_id', $login_user->group_id);
                        $this->session->set_userdata('user_id', $login_user->id);
                        $this->session->set_userdata('gravatar', $login_user->gravatar);
                        redirect(site_url());
                    } else {
                        $this->_data['login_error'] = "Wrong email or password, Please try again";
                        $this->display_view('home/index');
                    }
                }
            } else {
                $this->_data['validate_error'] = TRUE;
                $this->display_view('home/index');
            }
        } else {
            $this->display_view('home/index');
        }
    }

    function logout() {
        if ($this->session->userdata('user_id') != NULL) {
            $this->session->unset_userdata('user_id');
            $this->session->sess_destroy();
            redirect(base_url());
        }
    }

    function check_exist_email($email) {
        $email = $this->input->post('email');
        $query = $this->User_m->check_register_exist_fields('email', $email);
        if ($query->num_rows > 0) {
            $this->form_validation->set_message('check_exist_email', 'The %s was exist');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function check_exist_username($username) {
        $username = $this->input->post('identifiant');
        $query = $this->User_m->check_register_exist_fields('username', $username);
        if ($query->num_rows > 0) {
            $this->form_validation->set_message('check_exist_username', 'The %s was exist');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function register() {
        $this->_data['telephone'] = $this->input->post('telephone');
        $this->_data['mobilephone'] = $this->input->post('mobilephone');
        $this->_data['societe'] = $this->input->post('societe');

        $months = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
            "Oct", "Nov", "Dec");
        ini_set("date.timezone", "Europe/Paris");
        $this_day = now();
        $pattern_year = "%Y";
        $this->_data['str_year'] = $str_year = mdate($pattern_year, $this_day);

        for ($i = 0; $i < 12; $i++) {
            $month_data[$i + 1] = $months[$i];
        }
        for ($i = 0; $i < 31; $i++) {
            $day_data[$i + 1] = $i + 1;
        }
        for ($i = $str_year; $i > 1900; $i--) {
            $year_data[$i] = $i;
        }
        $this->_data['day'] = $day_data;
        $this->_data['month'] = $month_data;
        $this->_data['year'] = $year_data;

        $upload_flag = 0;

        $valid_config = array(
            array('field' => 'identifiant',
                'label' => 'Identifiant',
                'rules' => 'required|min_length[3]|xss_clean|callback_check_exist_username'
            ),
            array('field' => 'email',
                'label' => 'Email',
                'rules' => 'required|valid_email|trim|xss_clean|callback_check_exist_email'
            ),
            array('field' => 'password',
                'label' => 'Password',
                'rules' => 'required|trim|min_length[5]|matches[confirm_password]|md5'
            ),
            array('field' => 'confirm_password',
                'label' => 'Confirm Password',
                'rules' => 'required|trim'
            ),
            array('field' => 'nom',
                'label' => 'Nom',
                'rules' => 'required|trim|xss_clean'
            ),
            array('field' => 'prenom',
                'label' => 'Pre nom',
                'rules' => 'required|trim|xss_clean'
            ),
            array('field' => 'address',
                'label' => 'Address',
                'rules' => 'required|trim|xss_clean'
            ),
            array('field' => 'telephone',
                'label' => 'Telephone',
                'rules' => 'numeric'
            ),
            array('field' => 'mobilephone',
                'label' => 'Mobile Phone',
                'rules' => 'numeric'
            ),
        );
        $this->form_validation->set_rules($valid_config);

        if ($this->input->post('inscrire')) {

            //-----------------Upload photos-------------------------------//
            $image_path = '../assets/avatar';
            $thumb_path = $image_path . '/images';

            $config = array(
                'allowed_types' => "jpg|jpeg|gif|png",
                'upload_path' => $image_path,
                'max_size' => 10000
            );
            $this->_data['page_title'] = "Uploading...";
            $this->load->library('upload', $config);

            if ($this->upload->do_upload()) {
                $upload_info = $this->upload->data();
                $config = array(
                    'source_image' => $upload_info['full_path'], //get original image
                    'new_image' => $thumb_path, //save as new image //need to create thumbs first
                    'maintain_ratio' => true,
                    'width' => 300,
                    'height' => 200
                );
                $this->load->library('image_lib', $config); //load library
                $this->image_lib->resize(); //do whatever specified in config
                $upload_flag = 1;
            } else {
                $upload_info = null;
                $upload_flag = 0;
            }
            //---------------------End Upload photo-----------------------------//
            //validate form and register login infors

            if ($this->form_validation->run() === TRUE) {
                $email = $this->input->post('email');
                $username = $this->input->post('identifiant');
                $password = $this->input->post('password');
                $group_id = 3;
                $active = 1;
                $created_on = now();
                $data_login = array('email' => $email,
                    'username' => $username,
                    'password' => $password,
                    'created_on' => $created_on,
                    'group_id' => $group_id,
                    'active' => $active
                );
                $this->User_m->register_user($data_login);
                $user_id_row = $this->User_m->get_user_register_id($email)->row();
                $user_id = $user_id_row->id;

                //----register User Profile---//
                $avatar = $upload_info['file_name'];
                $nom = $this->input->post('nom');
                $prenom = $this->input->post('prenom');
                $naissance = mktime(0, 0, 0, $this->input->post('birth_month'), $this->input->post('birth_date'), $this->input->post('birth_year'));
                $company = $this->input->post('societe');
                $gender = $this->input->post('genre');
                $telephone = $this->input->post('telephone');
                $mobilephone = $this->input->post('mobilephone');
                $address = $this->input->post('address');

                if ($upload_flag == 1) {
                    $data_profiles = array(
                        'user_id' => $user_id,
                        'display_name' => $prenom . $nom,
                        'first_name' => $prenom,
                        'last_name' => $nom,
                        'company' => $company,
                        'dob' => $naissance,
                        'gender' => $gender,
                        'phone' => $telephone,
                        'mobile' => $mobilephone,
                        'address' => $address,
                        'gravatar' => $upload_info['file_name']
                    );
                } else {
                    $data_profiles = array(
                        'user_id' => $user_id,
                        'display_name' => $prenom . ' ' . $nom,
                        'first_name' => $prenom,
                        'last_name' => $nom,
                        'company' => $company,
                        'dob' => $naissance,
                        'gender' => $gender,
                        'phone' => $telephone,
                        'mobile' => $mobilephone,
                        'address' => $address
                    );
                }
                $this->User_m->register_user_profiles($data_profiles);
                $this->session->set_userdata('user_id', $user_id);
                $this->session->set_userdata('user_name', $username);
                $this->display_view('home/user/register_success');
            } else {
                $this->_data['error_flag'] = 1;
                $this->display_view('home/user/register_form');
            }
        } else {
            //not isset $_POST['inscrire']
            $this->display_view('home/user/register_form');
        }
    }

    function check_current_password($password) {
        $user_id = $this->session->userdata('user_id');
        $password = md5($this->input->post('current_password'));
        $query = $this->User_m->get_current_password($user_id, $password);
        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            $this->form_validation->set_message('check_current_password', 'The %s was wrong');
            return FALSE;
        }
    }

    function change_password() {
        is_user();
        $error_flag = 0;
        $config = array(
            array('field' => 'current_password',
                'label' => 'Current Password',
                'rules' => 'required|md5|trim|callback_check_current_password'
            ),
            array('field' => 'new_password',
                'label' => 'New Password',
                'rules' => 'required|trim|matches[confirm_new_password]|min_length[5]|md5'
            ),
            array('field' => 'confirm_new_password',
                'label' => 'Confirm new password',
                'rules' => 'required'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->input->post('btn_change_pass')) {
            if ($this->form_validation->run() === TRUE) {
                $current_pass = $this->input->post('current_password');
                $new_pass = $this->input->post('new_password');
                $user_id = $this->session->userdata('user_id');
                $data = array('password' => $new_pass);
                $this->User_m->change_password($user_id, $data);
                $this->display_view('home/user/change_pass_success');
            } else {
                $this->_data['error_flag'] = 1;
                $this->display_view('home/user/change_pass_form');
            }
        } else {//if btn_change_pass not clicked
            $this->display_view('home/user/change_pass_form');
        }
    }

    function change_avatar() {
        is_user();
        $user_id = $this->session->userdata('user_id');
        $query_avatar = $this->User_m->get_avatar_user($user_id);
        $this->_data['avatar'] = $query_avatar->row()->gravatar;

        if ($this->input->post("btn_change_avatar")) {
            $image_path = '../assets/avatar';
            $thumb_path = $image_path . '/images';

            $config = array(
                'allowed_types' => "jpg|jpeg|gif|png",
                'upload_path' => $image_path,
                'max_size' => 10000
            );

            $this->_data['page_title'] = "Uploading...";
            $this->load->library('upload', $config);

            if ($this->upload->do_upload()) {
                $upload_info = $this->upload->data();
                $config = array(
                    'source_image' => $upload_info['full_path'], //get original image
                    'new_image' => $thumb_path, //save as new image //need to create thumbs first
                    'maintain_ratio' => true,
                    'width' => 300,
                    'height' => 200
                );
                $this->load->library('image_lib', $config); //load library
                $this->image_lib->resize(); //do whatever specified in config
                $data = array('gravatar' => $upload_info['file_name']);
                $this->User_m->change_avatar($user_id, $data);
                $this->display_view('home/user/change_avatar_success');
            } else {
                $this->display_view('home/user/change_avatar_form');
            }
        } else {//not isset post("btn_change_avatar")
            $this->display_view('home/user/change_avatar_form');
        }
    }

}